<?php

namespace app\agent\controller;
use app\admin\model\Admin;
use app\common\controller\Agent;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Images;
use app\common\model\Message;
use app\common\model\PlatformMoneyRecord;
use think\Config;
use think\Db;
use think\Exception;
use think\Queue;

/**
 * 商家管理
 *
 * @icon fa fa-user
 */
class Recharge extends Agent
{

    protected $relationSearch = true;
    protected $searchFields = 'shop_name';
    protected $multiFields = 'status';

    protected $model = null;
    protected $agent_id = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Recharge');
        $agent_info = session('agent');
        $this->agent_id = $agent_info['id'];
    }

    /**
 * 查看
 */
    public function index($ids=null)
    {
        $this->view->assign("shop_id", $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $filter = $this->request->get("filter", '');
            $filter = (array)json_decode($filter, true);
            $list = $this->model->with(['shop'])->where($where)->where(['recharge.agent_id'=>$this->agent_id])->order($sort, $order)->paginate($limit);
            if (!isset($filter['status'])){ //全统计
//                $ljwc = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',3)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money'); //累计完成
//                $ljdqr = $this->model->with(['shop','agents'])->where($where)->where('recharge.status','in',[0,1,2])->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//累计待确认
//                $dddlscz = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',0)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//等待代理商充值
//                $ddptqr= $this->model->with(['shop','agents'])->where($where)->where('recharge.status',1)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//等待平台确认
//                $sjqr = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',2)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//等待商家确认

                $ljwc = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',3)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money'); //累计完成
                $ljdlcz = $this->model->with(['shop','agents'])->where($where)->where('recharge.status','in',[1,2,3])->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//累计代理商充值
                $ljptcz = $this->model->with(['shop','agents'])->where($where)->where('recharge.status','in',[2,3])->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//累计平台充值
                $dddlscz = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',0)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//等待代理商充值
                $ddptqr= $this->model->with(['shop','agents'])->where($where)->where('recharge.status',1)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//等待平台确认
                $sjqr = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',2)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//等待商家确认
                $count = [['name'=>'累计完成充值','value'=>$ljwc],
                    ['name'=>'等待代理商充值','value'=>$dddlscz],
                    ['name'=>'累计代理充值','value'=>$ljdlcz],
                    ['name'=>'等待平台充值','value'=>$ddptqr],
                    ['name'=>'累计平台充值','value'=>$ljptcz],
                    ['name'=>'等待商家确认','value'=>$sjqr]
                ];
//                $count = [['name'=>'累计完成充值','value'=>$ljwc],['name'=>'累计待确认','value'=>$ljdqr],['name'=>'等待代理充值','value'=>$dddlscz],['name'=>'等待平台充值','value'=>$ddptqr],['name'=>'等待商家确认','value'=>$sjqr]];
            }else{ //按类别统计
                if ($filter['status'] == 3){
                    $ljwc = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',3)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money'); //累计完成
                    $count = [['name'=>'累计完成充值','value'=>$ljwc],
                        ['name'=>'等待代理商充值','value'=>0],
                        ['name'=>'累计代理充值','value'=>0],
                        ['name'=>'等待平台充值','value'=>0],
                        ['name'=>'累计平台充值','value'=>0],
                        ['name'=>'等待商家确认','value'=>0]
                    ];




//                    $ljwc = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',3)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money'); //累计完成
//                    $count = [['name'=>'累计完成充值','value'=>$ljwc],['name'=>'累计待确认','value'=>0],['name'=>'等待代理充值','value'=>0],['name'=>'等待平台充值','value'=>0],['name'=>'等待商家确认','value'=>0]];
                }elseif ($filter['status'] == 0){
                    $ljdqr = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',0)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//累计待确认
                    $count = [['name'=>'累计完成充值','value'=>0],
                        ['name'=>'等待代理商充值','value'=>$ljdqr],
                        ['name'=>'累计代理充值','value'=>0],
                        ['name'=>'等待平台充值','value'=>0],
                        ['name'=>'累计平台充值','value'=>0],
                        ['name'=>'等待商家确认','value'=>0]
                    ];

//                    $ljdqr = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',0)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//累计待确认
//                    $count = [['name'=>'累计完成充值','value'=>0],['name'=>'累计待确认','value'=>$ljdqr],['name'=>'等待代理充值','value'=>$ljdqr],['name'=>'等待平台充值','value'=>0],['name'=>'等待商家确认','value'=>0]];
                }elseif ($filter['status'] == 1){
                    $ddptqr= $this->model->with(['shop','agents'])->where($where)->where('recharge.status',1)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//等待平台确认
                    $count = [['name'=>'累计完成充值','value'=>0],
                        ['name'=>'等待代理商充值','value'=>0],
                        ['name'=>'累计代理充值','value'=>0],
                        ['name'=>'等待平台充值','value'=>$ddptqr],
                        ['name'=>'累计平台充值','value'=>0],
                        ['name'=>'等待商家确认','value'=>0]
                    ];


//                    $ddptqr= $this->model->with(['shop','agents'])->where($where)->where('recharge.status',1)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//等待平台确认
//                    $count = [['name'=>'累计完成充值','value'=>0],['name'=>'累计待确认','value'=>$ddptqr],['name'=>'等待代理充值','value'=>0],['name'=>'等待平台充值','value'=>$ddptqr],['name'=>'等待商家确认','value'=>0]];
                }elseif ($filter['status'] == 2){
                    $sjqr = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',2)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//等待商家确认
                    $count = [['name'=>'累计完成充值','value'=>0],
                        ['name'=>'等待代理商充值','value'=>0],
                        ['name'=>'累计代理充值','value'=>0],
                        ['name'=>'等待平台充值','value'=>0],
                        ['name'=>'累计平台充值','value'=>0],
                        ['name'=>'等待商家确认','value'=>$sjqr]
                    ];

//                    $sjqr = $this->model->with(['shop','agents'])->where($where)->where('recharge.status',2)->where(['recharge.agent_id'=>$this->agent_id])->sum('recharge.money');//等待商家确认
//                    $count = [['name'=>'累计完成充值','value'=>0],['name'=>'累计待确认','value'=>$sjqr],['name'=>'等待代理充值','value'=>0],['name'=>'等待平台充值','value'=>0],['name'=>'等待商家确认','value'=>$sjqr]];
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items(),'extend'=>['count'=>$count]);
            return json($result);
        }
        if ($ids !== null)
            $this->assignconfig('shop_id',$ids);
        return $this->view->fetch();
    }


    /**
     * 确认充值
     * @return string
     * @throws \think\Exception
     */
    public function confirm($ids = null)
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $row = $this->model->get(['id'=>$params['id'],'agent_id'=>$this->agent_id])->toArray();
                if (!$row) {
                    $this->error(__('No Results were found'));
                }
                Db::startTrans();
                try {
                    $params['status'] = 1;
                    $result = $this->model->update(['id'=>$params['id'],'status'=>1,'agent_record'=>$params['reocrd_images'],'agenttime'=>time()]);
                    $shop_info = \app\common\model\Shop::get(['id'=>$row['shop_id']]);
                    Message::create(['content'=>$shop_info['shop_name'].'发起一笔充值申请,请及时查看！']);
                    //平台收益记录
                    PlatformMoneyRecord::create(['type'=>1,'detail_type'=>PlatformMoneyRecord::DETAIL_TYPE_AGENT_RECHARGE,'money'=>$row['money'],'remark'=>$row['id'],'createtime'=>time()]);
                    Db::commit();
                    $admins = Admin::where(['status'=>'normal','member_id'=>['gt',0]])->select();
                    foreach ($admins as $v){
                            Queue::push(\app\job\Message::class,[
                                'member_id'=>$v['member_id'],
                                'template_id'=>config('wechat_gzh')['gzh_template']['daichuligongdan'],
                                'data'=>[
                                    'thing41'=>"请处理商家发起的充值申请",
                                    'thing14'=>$shop_info['shop_name'],
                                    'time15'=>date('Y-m-d H:i'),
                                    'short_thing5'=>"待处理"
                                ]
                            ],'message');
                    }

                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("id", $ids);
        return $this->view->fetch();
    }

    /**
     * 确认充值
     */
    public function confirms($ids = NULL)
    {
        Db::startTrans();
        try{
            if (empty($ids)){
                throw new Exception('充值记录ID缺失');
            }
            $row = $this->model->get(['id' => $ids]);
            if (!$row) {
                throw new Exception('No Results were found');
            }
            if ($row->status !=0){
                throw new Exception('记录非待充值状态');
            }
            $result = $row->save(['status'=>1]);
            if ($result === false) {
                throw new Exception('状态更新失败');
            }
            $shop_row = model('shop')->get(['id' => $row->shop_id]);
            if (!$shop_row) {
                throw new Exception('No Shop Results were found');
            }
            $flag = $shop_row->setInc('money',$row->money);
            if (!$flag){
                throw new Exception('商家余额更新失败');
            }
            Db::commit();
            $this->success();
        }catch (Exception $e){
            Db::rollback();
            $this->error($e->getMessage());
        }
    }

    /**
     * 上传文件
     */
    public function upload()
    {
        Config::set('default_return_type', 'json');
        //必须设定cdnurl为空,否则cdnurl函数计算错误
        Config::set('upload.cdnurl', '');
        $attachment = null;
        //默认普通上传文件
        $file = $this->request->file('file');
        try {
            $upload = new Upload($file);
            $attachment = $upload->upload('uploads/recharge/'.md5(time()));
        } catch (UploadException $e) {
            $this->error($e->getMessage());
        }

        $this->success(__('Uploaded successful'), '', ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
    }




}
